import { RouteReuseStrategy, DefaultUrlSerializer, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';

export class MyRouterReuseStrategy implements RouteReuseStrategy {

    public static _cacheRouters: { [key: string]: any } = {};


    //删除快照
    public static Remove(name:string){
        if(name&&MyRouterReuseStrategy._cacheRouters[name]) delete MyRouterReuseStrategy._cacheRouters[name];
    }

    /** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */
    public shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return !!route.parent.routeConfig.data && !!route.parent.routeConfig.data.snapshot;
    }

    /** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */
    public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        MyRouterReuseStrategy._cacheRouters[route.parent.routeConfig.path] = {
            snapshot: route,
            handle: handle
        };
    }

    /** 是否允许还原路由 */
    public shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!MyRouterReuseStrategy._cacheRouters[route.parent.routeConfig.path];
    }

    /** 从缓存中获取快照，若无则返回nul */
    public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if(!route.parent) return null;
        if(!route.parent.routeConfig) return null;
        if(!route.parent.routeConfig.path) return null;
        if (MyRouterReuseStrategy._cacheRouters[route.parent.routeConfig.path])
            return MyRouterReuseStrategy._cacheRouters[route.parent.routeConfig.path].handle;
        else return null;
    }

    /** 进入路由触发，判断是否使用系统默认路由事件 */
    public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        if(!future.routeConfig) return true;
        if(future.routeConfig.loadChildren) return true;
        if(future.routeConfig&&curr.routeConfig) return future.routeConfig === curr.routeConfig;
    }
}